package cn.gdcp.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView imgnext;
    private Button btnnext;
    private int []arr={R.drawable.dog1,R.drawable.dog2,R.drawable.dog3,R.drawable.dog4,R.drawable.dog5};
    private int index=0;
    private Handler handler;
    private final int MSG_CHANGE=1001;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           handler=new Handler(new Handler.Callback() {
               @Override
               public boolean handleMessage(Message msg) {
                   if(msg.what==MSG_CHANGE){
                       index = (index + 1) % arr.length;
                       imgnext.setImageResource(arr[index]);
                       return true;
                   }
                   return false;
               }
           });
        imgnext= (ImageView) findViewById(R.id.img);
        btnnext= (Button) findViewById(R.id.btn);
            btnnext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (true) {
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                Message message=new Message();
                                message.what=MSG_CHANGE;
                                handler.sendMessage(message);
//                                index = (index + 1) % arr.length;
//                                imgnext.setImageResource(arr[index]);
                            }
                        }
                    }).start();

                }
            });
    }
}
